package com.xiaoq.matrix.repository.impl;

import java.util.ArrayList;
import java.util.List;

import org.mongodb.morphia.Datastore;
import org.mongodb.morphia.query.Query;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.xiaoq.coms.util.IdGenerator;
import com.xiaoq.matrix.entity.QRadioEntity;
import com.xiaoq.matrix.repository.IQRadioRepository;
import com.xiaoq.vo.PagingVo;

@Repository
public class QRadioRepositoryImpl implements IQRadioRepository {
	
	@Autowired
	private Datastore datastore;
	
	private static final Logger LOG = LoggerFactory.getLogger(QRadioRepositoryImpl.class);

	@Override
	public List<QRadioEntity> findTopTen(String type,PagingVo pvo) {
		int ps = pvo.getPs();
		int pn = (pvo.getPn() - 1) * ps;
		Query<QRadioEntity> topTenQuery = datastore.find(QRadioEntity.class);
		topTenQuery.field("type").equal(type);
		Long total = 0L;
		List<QRadioEntity> topTenList = new ArrayList<>();
		if (topTenQuery != null && topTenQuery.count() != 0L) {
			total = topTenQuery.count();
			topTenQuery.order("-sortNum").order("-pubTime").offset(pn).limit(ps);
			topTenList = topTenQuery.asList();
		}
		pvo.setTc(total);
		return topTenList;
	}

	@Override
	public QRadioEntity save(QRadioEntity topTen) {
		topTen.setId(new IdGenerator().nextId());
		datastore.save(topTen);
		return topTen;
	}

}
